import React, { useMemo,useState,useEffect } from 'react';
import { splitPrice, transform2px, transformConfig } from '@/utils/customModule';
import Taro from '@tarojs/taro';
import utils from '@/utils/index';
import classNames from 'classnames';
import { View,Image, ScrollView } from '@tarojs/components';
import Icon from '../Icon';
import './index.scss';
import { defaultVisibleEnums } from './../moduleConstants';
import { appProductListServer } from '@/services/productList';
import {
  recommendGoodsCartStyle,
  recommendGoodsGoodsAlign,
  recommendGoodsStyle,
} from '../ModuleGoods/constants';

const GoodsStyleName = {
  [recommendGoodsStyle.line]: 'flatten',
  [recommendGoodsStyle.card]: 'cards',
  [recommendGoodsStyle.border]: 'border',
};
const styleConfig = {
  item: ['borderRadius'],
  background: (styleSetting) => {
    if (styleSetting.goodsStyle === recommendGoodsStyle.line) {
      return {
        // backgroundColor: '#fff',
      };
    }
    return {
      // backgroundColor: styleSetting.opacity === defaultVisibleEnums.show ? '#fff' : undefined,
    };
  },
  img: [(styleSetting) => {
    if (styleSetting.goodsStyle !== recommendGoodsStyle.line) {
      return undefined;
    }
    return {
      borderRadius: transform2px(styleSetting.borderRadius),
    };
  }],
};

const LeftPanel = ({ content, product }) => {
  const { scribingPrice, price, saleNum } = product;
  const getCartStyle = () => {
    if (content?.showCart !== defaultVisibleEnums.show) {
      return null;
    }
    if (content?.cartStyle == recommendGoodsCartStyle.one) {
      return <Icon name="icon_shopping" className="goods-cart" size={34} />;
    }
    if (content?.cartStyle == recommendGoodsCartStyle.two) {
      return <Icon name="icon_add" className="goods-cart" size={34} />;
    }
    return null;
  };

  return (
    <View className="goods-panel goods-left-panel">
      <ProductTitle {...{ content, product }} />
      <View>
        {content?.showGoodsSaleNum == defaultVisibleEnums.show && (
          <View className="goods-sales">已售{saleNum ?? 0}件</View>
        )}
        <View className="goods-line">
          <View className="goods-price omit">
            <SplitPrice price={price} />
            {content?.showSalePrice == defaultVisibleEnums.show && scribingPrice !== undefined && (
              <View className="del-price">¥{scribingPrice}</View>
            )}
          </View>
          {getCartStyle()}
        </View>
      </View>
    </View>
  );
};

const SplitPrice = ({ price }) => {
  const [priceLeft, priceRight] = splitPrice(price);
  return (
    <View className="sale-price customePageStyle">
      <View className="price-0">¥</View>
      <View className="price-1">{priceLeft}</View>
      <View className="price-2">.{priceRight}</View>
    </View>
  );
};

const ProductTag = ({ product, hasTag }) => {
  if (!hasTag) {
    return null;
  }
  return (
    <View className="tags omit customePageStyle">
      {product?.tagList?.map((str) => {
        return (
          <View className="tag customeSalesPromotionLabelStyle" key={str}>
            <View className="txt">{str}</View>
          </View>
        );
      })}
    </View>
  );
};
const ProductTitle = ({ content, product }) => {
  const hasTag = content?.showTag == defaultVisibleEnums.show && product?.tagList?.length;
  return (
    <>
      <View className={classNames('goods-title', { tag: hasTag })}>{product?.title}</View>
      <ProductTag {...{ product, hasTag }} />
    </>
  );
};

const CenterPanel = ({ content, product }) => {
  const { price } = product;
  return (
    <View className="goods-panel goods-center-panel">
      <ProductTitle {...{ content, product }} />
      <View className="goods-line">
        <SplitPrice price={price} />
        <View className={classNames('goods-cart customePageBackgroundStyle', {
          borderRadius: content.cartStyle == recommendGoodsCartStyle.third,
        })} >
          <View className="txt">{content?.cartText}</View>
        </View>
      </View>
    </View>
  );
};
const ModuleGoodsGroup = ({ componentCfg = {} }) => {
  const { styleSettingRender, content,styleSetting } = componentCfg;
  const style = transformConfig({...styleSetting,...styleSettingRender}, styleConfig);
  const wrapStyles = useMemo(() => {
    return {
      paddingTop: styleSettingRender.paddingTop,
      paddingBottom: styleSettingRender.paddingBottom,
      background: styleSettingRender.backgroundColor,
      color: styleSettingRender.color,
      fontSize: styleSettingRender.fontSize,
    };
  }, [styleSettingRender]);
  const [appProductList, setAppProductList] = useState([]);
  const [curTabs, setcurTabs] = useState(0)
  const [scrollHeight, setscrollHeight] = useState(0)
  const [filters, setfilters] = useState({
    page:1,
    pageSize:10
  })
  useEffect(()=>{
    if (!content) {
      return;
    }
    _getList({
      page:1,
      sort:content?.items[0]?.sort,
      productReleaseName: content?.items[0]?.label,
      productReleaseGroupId: content?.items[0]?.value
    })
  },[content])
  useEffect(()=>{
    if(appProductList.length){
      const query = Taro.createSelectorQuery()
      query.select('.GroupGoods .goods-item').boundingClientRect().exec((res) => {
        if (res && res[0]) {
          setscrollHeight((res[0].height || 0) *2)
        }
      })
    }
  },[appProductList])
  const _getList =(e,func)=>{
    Taro.showLoading({title:'加载中...'})
    const data = {
      appid: Taro.$sassAppId,
      type: 4,
      ...filters,
      ...e
    }
    appProductListServer(data).then((res) => {
      Taro.hideLoading()
      return res?.content ?? {};
    }).then(({ list,pagination }) => {
      setfilters({
        ...data,
        totalCount:pagination.totalCount || 0
      })
      if(func) return func(list)
      setAppProductList(list);
    });
  }
  return (
    <View className="ModuleGoodsGroup" style={wrapStyles}>
      <View className="de-group">
        <View className="de-group__list">
          {content?.items?.map((item, index) => (<>
            <View className={`de-group__item ${curTabs == index?'active':''}`} onClick={() =>{
              setcurTabs(index)
              _getList({
                page:1,
                sort:item.sort,
                productReleaseName: item.label,
                productReleaseGroupId: item.value
              })
            }} key={item.value} >
              {item.label}
            </View>
            {content.showDelimiter == defaultVisibleEnums.show &&
              index !== content?.items?.length - 1 && (
                <View className="de-group__spacing" key={'limit' + item.value}>
                  |
                </View>
              )}
          </>))}
        </View>
        <View className="de-group__filter" />
      </View>
      <ScrollView scrollY className="GroupGoods" onScrollToLower={e=>{
        if(filters.totalCount > appProductList.length && appProductList.length<content.items[curTabs]?.pageSize){
          _getList({page:filters.page+1},data=>{
            setAppProductList([...appProductList,...data])
          })
        }
      }} style={{ ...style.module, ...style.background, maxHeight:scrollHeight }}>
        <View className={classNames('goods-container', { [GoodsStyleName[styleSetting.goodsStyle]]: true })}>
          {appProductList?.slice(0,content?.items[curTabs]?.pageSize).map((product) => {
            const { id, url, label, isSoldOut } = product;
            const panelProps = { content, product };
            return (
              <View className="goods-item" key={id} style={{...style.item,width:`calc(${100/styleSetting.listStyle}% - ${styleSetting.goodsMargin || 0}px)`,marginBottom:`${styleSetting.goodsMargin+(styleSetting.goodsMargin/2) || 0}px`}} onClick={() => {
                  Taro.navigateTo({
                    url:`/mainSubPack/goodsDetail/index?id=${id}`
                  })
              }} >
                {label && (
                  <View className="goods-label customePageBackgroundStyle">
                    <View className="txt">{label}</View>
                  </View>
                )}
                <View className="goods-img-wrap">
                  <Image className="goods-img" src={url} style={style.img} />

                  {content?.saleOut == defaultVisibleEnums.show && isSoldOut && (
                    <View className="goods-sold-out">
                      <View className="sold-out-container">
                        <View className="txt">售罄</View>
                      </View>
                    </View>
                  )}
                </View>
                {content?.goodsAlign == recommendGoodsGoodsAlign.left && (
                  <LeftPanel {...panelProps} />
                )}
                {content?.goodsAlign == recommendGoodsGoodsAlign.center && (
                  <CenterPanel {...panelProps} />
                )}
              </View>
            );
          })}
          {/* 占位 */}
          {appProductList?.length % 3 === 2 && (
            <View className="goods-item-placeholder" style={{...style.item,width: `calc(${100/styleSetting.style}% - ${styleSetting.goodsMargin || 0}px)`}} />
          )}
        </View>
      </ScrollView>
    </View>
  );
};
export default ModuleGoodsGroup;
